# Locate libusb
#
# This module accepts the following environment variables:
#
#    LIBUSB_DIR or LIBUSB_ROOT - Specify the location of LIBUSB
#
# This module defines the following CMake variables:
#
#    LIBUSB_FOUND - True if libusb is found
#    LIBUSB_LIBRARY - A variable pointing to the LIBUSB library
#    LIBUSB_INCLUDE_DIR - Where to find the headers
#
# $LIBUSBDIR is an environment variable that would
# correspond to the ./configure --prefix=$LIBUSB_DIR
# used in building usb.
#
# This makes the presumption that you are include usb.h like
#
#include "usb.h"

FIND_PATH(LIBUSB_INCLUDE_DIR usb.h
  HINTS
    $ENV{LIBUSB_DIR}
    $ENV{LIBUSB_ROOT}
  PATH_SUFFIXES
     include
  PATHS
      /sw # Fink
      /opt/local # DarwinPorts
      /opt/csw # Blastwave
      /opt
)

IF(UNIX)
    # Use libusb-config to obtain the library version (this should hopefully
    # allow us to -lusb)
    FIND_PROGRAM(LIBUSB_CONFIG libusb-config
        HINTS
          $ENV{LIBUSB_DIR}
          $ENV{LIBUSB_ROOT}
        PATH_SUFFIXES bin
        PATHS
            /sw # Fink
            /opt/local # DarwinPorts
            /opt/csw # Blastwave
            /opt
    )

    if(LIBUSB_CONFIG)
        exec_program(${LIBUSB_CONFIG} ARGS --libs OUTPUT_VARIABLE LIBUSB_CONFIG_LIBS)
        if(LIBUSB_CONFIG_LIBS)
            string(REGEX MATCHALL "-l[^ ]+" _libusb_dashl ${LIBUSB_CONFIG_LIBS})
            string(REGEX REPLACE "-l" "" _libusb_lib "${_libusb_dashl}")
            string(REGEX MATCHALL "-L[^ ]+" _libusb_dashL ${LIBUSB_CONFIG_LIBS})
            string(REGEX REPLACE "-L" "" _libusb_libpath "${_libusb_dashL}")
        endif()
    endif()
endif()

FIND_LIBRARY(LIBUSB_LIBRARY 
  NAMES ${_libusb_lib} libusb LIBUSB
  HINTS
     $ENV{LIBUSB_DIR}
     $ENV{LIBUSB_ROOT}
     ${_libusb_libpath}
  PATH_SUFFIXES lib64 lib
  PATHS
    /sw
    /opt/local
    /opt/csw
    /opt
    /usr/freeware
)

include(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LIBUSB DEFAULT_MSG LIBUSB_LIBRARY LIBUSB_INCLUDE_DIR)

set(LIBUSB_LIBRARIES ${LIBUSB_LIBRARY})
set(LIBUSB_INCLUDE_DIRS ${LIBUSB_INCLUDE_DIR})
